/*
 * Copyright 2007 National Bioinformatics Network
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dgbgui.gui;

import java.awt.geom.Rectangle2D;

public class BoundingRectangle {
    
    public BoundingRectangle() {
        m_rect = new Rectangle2D.Float(0,0,0,0);
    }
    
    public BoundingRectangle(BoundingRectangle other) {
        m_rect = new Rectangle2D.Float(other.m_rect.x,other.m_rect.y,other.m_rect.width,other.m_rect.height);
        normalise();
    }
    
    public BoundingRectangle(float x, float y, float width, float height) {
        m_rect = new Rectangle2D.Float(x,y,width,height);
        normalise();
    }
    
    public void set(BoundingRectangle rect) {
        m_rect = rect.m_rect;
        normalise();
    }
    
    /**
     * Add one rectangle ort another. Equivalent to a union operation.
     * @param rect the rectangle to add
     */
    public void add(BoundingRectangle rect) {
        rect.normalise();
        if ( rect.getX() < m_rect.x ) {
            float dx = rect.getX() - m_rect.x;
            m_rect.width = m_rect.width - dx;
            m_rect.x = rect.getX();

        }
        if ( rect.getY() < m_rect.y ) {
            float dy = rect.getY() - m_rect.y;
            m_rect.height = m_rect.height - dy;
            m_rect.y = rect.getY();
        }
        if ( rect.getX() + rect.getWidth() > m_rect.x + m_rect.width ) {
            m_rect.width = rect.getX() + rect.getWidth() - m_rect.x;
        }
        if ( rect.getY() + rect.getHeight() > m_rect.y + m_rect.height ) {
            m_rect.height = rect.getY() + rect.getHeight() - m_rect.y;
        }
    }
    
    /**
     * Normalise the rectangle so that width and height are > 0
     *
     */
    private void normalise() {
        if ( m_rect.width < 0 ) {
            m_rect.x = m_rect.x + m_rect.width;
            m_rect.width = -m_rect.width;
        }
        if ( m_rect.height < 0 ) {
            m_rect.y = m_rect.y + m_rect.height;
            m_rect.height = -m_rect.height;
        }
    }
    
    public boolean equals(BoundingRectangle other) {
        return m_rect.equals(other.m_rect);
    }
    
    public float getX() {
        return m_rect.x;
    }
    
    public float getY() {
        return m_rect.y;
    }
    
    public float getWidth() {
        return m_rect.width;
    }
    
    public float getHeight() {
        return m_rect.height;
    }
    
    private Rectangle2D.Float m_rect;

}
